<template>
  <div v-move class="card">
    <div class="header">标题</div>
    <div class="content">内容</div>
  </div>
</template>

<script setup lang="ts">
import type { Directive } from 'vue';
// v-move 移动指令
const vMove: Directive<HTMLElement> = (el) => {
  const header = el.firstChild as HTMLElement;
  // 1.给 header 绑定 mousedown 事件
  const mousedown = (e: MouseEvent) => {
    // 2.给 header 绑定 mousemove 事件
    // 鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
    let X = e.clientX - el.offsetLeft;
    let Y = e.clientY - el.offsetTop;
    const mousemove = (e: MouseEvent) => {
      el.style.left = e.clientX - X + 'px';
      el.style.top = e.clientY - Y + 'px';
    };
    document.addEventListener('mousemove', mousemove);
    // 3. 当松开鼠标的时候，移除鼠标移动事件
    document.addEventListener('mouseup', () => {
      document.removeEventListener('mousemove', mousemove);
    });
  };
  header.addEventListener('mousedown', mousedown);
};
</script>

<style lang="scss" scoped>
.card {
  position: absolute;
  width: 300px;
  height: 250px;
  border: 1px solid black;
  .header {
    height: 50px;
    background-color: pink;
    cursor: move;
  }
  .content {
    height: 400px;
  }
}
</style>
